export default class Payment {
  constructor (options) {
    if (options.sandbox) {
      options.gateway = 'https://sandbox.itunes.apple.com/verifyReceipt'
    }
    options = Object.assign({
      gateway: 'https://buy.itunes.apple.com/verifyReceipt',
      timeout: 5000,
      // if your IAP is not a subscription, let it empty string(like this: ''), else use you own password
      password: ''
    }, options)

    this.options = options
  }

  async _request (params) {
    const requestOptions = {
      method: 'POST',
      contentType: 'json',
      dataType: 'json',
      data: params,
      timeout: this.options.timeout
    }
    const { status, data } = await uniCloud.httpclient.request(
      this.options.gateway,
      requestOptions
    )
    if (status !== 200) throw new Error('request fail')
    return this._parse(data)
  }

  _parse (data) {
    const tradeState = this._tradeState(data.status)
    if (data.status === 0) {
      return {
        transactionId: data.receipt.transaction_id,
        receipt: data.receipt,
        ...tradeState
      }
    }
    return tradeState
  }

  _tradeState (status) {
    let tradeState = 'PAYERROR'
    let errMsg = ''
    switch (status) {
      case -1:
        tradeState = 'NOTPAY'
        break
      case 0:
        tradeState = 'SUCCESS'
        break
      default:
        errMsg = 'Error status [' + status + ']'
        break
    }

    return {
      tradeState: tradeState,
      errMsg: errMsg
    }
  }

  async verifyReceipt (params) {
    params = {
      'receipt-data': params.receiptData,
      password: params.password || this.options.password
    }
    const result = await this._request(params)
    return result
  }
}
